import org.apache.shiro.SecurityUtils
import org.apache.shiro.authc.AuthenticationException
import org.apache.shiro.authc.UsernamePasswordToken
import org.apache.shiro.web.util.SavedRequest
import org.apache.shiro.web.util.WebUtils
import org.apache.shiro.grails.ConfigUtils
import org.bjou.*
import org.apache.shiro.crypto.hash.Sha256Hash

class AuthController {
    def shiroSecurityManager
    
    
    
     def changePassword()
    {
         if(params.newPassword!=params.confirmPassword)
         {
             flash.message = "二次输入密码不一致"
               return
         }
         if(params.oldPassword)
         {
             params.oldPassword = new Sha256Hash(params.oldPassword).toHex()
             def shiroUserInstance = ShiroUser.findByUsernameAndPasswordHash(session.user.username,params.oldPassword)
              if (!shiroUserInstance) {
                flash.message = "旧密码错误"
               return
                }
            shiroUserInstance.passwordHash =  new Sha256Hash(params.newPassword).toHex()
            shiroUserInstance.save(flush: true)
             flash.message = "密码已修改"
              //redirect(action: "index")
         }
        
         
    }

    def index = { 
        if(!session.user)
        {
             redirect(action: "login", params: params) 
        }
       
       
    }
    
    def reg = {
        [userBaseinfoInstance: new UserBaseinfo(params)]
    }

    def login = {
        return [ username: params.username, rememberMe: (params.rememberMe != null), targetUri: params.targetUri ]
    }

    def signIn = {
        print params
        def authToken = new UsernamePasswordToken(params.username, params.password as String)

        // Support for "remember me"
        if (params.rememberMe) {
            authToken.rememberMe = true
        }
        
        // If a controller redirected to this page, redirect back
        // to it. Otherwise redirect to the root URI.
        def targetUri = params.targetUri ?: "/"
        
        
        // Handle requests saved by Shiro filters.
        def savedRequest = WebUtils.getSavedRequest(request)
        if (savedRequest) {
            targetUri = savedRequest.requestURI - request.contextPath
            if (savedRequest.queryString) targetUri = targetUri + '?' + savedRequest.queryString
        }
        
        try{
            // Perform the actual login. An AuthenticationException
            // will be thrown if the username is unrecognised or the
            // password is incorrect.
            SecurityUtils.subject.login(authToken)
            def user =ShiroUser.findByUsername(params.username)
            session.user = user
            
            def userbaseinfo = UserBaseinfo.findByUser(user)
            if(userbaseinfo)
            {
               session.userbaseinfo = userbaseinfo 
            }
           
            def role = ShiroRole.findByUser(user.id).list().get(0)
            session.role = role
            //session.roleName = role.name
            switch(role.name){
                 case "分校角色":
                 def branch = Branch.findByUser(user.id).list().get(0)
                 session.branch = branch
                 break
                 case "系部角色":
                 def department = Department.findByUser(user.id).list().get(0)
                 session.department = department
                 break
                 case "管理员":
                 session.admin = 1
                 break
            
            }
            
            def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
            session.currentTerm = currentTerm
//            //TODO 修改为获取角色列表
//            def user =ShiroUser.findByUsername(params.username)
//            session.user = user

            log.info "Redirecting to '${targetUri}'."
            if(params.message)
            {
                flash.message = params.message
            }
            redirect(uri: targetUri)
        }
        catch (AuthenticationException ex){
            // Authentication failed, so display the appropriate message
            // on the login page.
            log.info "Authentication failure for user '${params.username}'."
            flash.message = message(code: "login.failed")

            // Keep the username and "remember me" setting so that the
            // user doesn't have to enter them again.
            def m = [ username: params.username ]
            if (params.rememberMe) {
                m["rememberMe"] = true
            }

            // Remember the target URI too.
            if (params.targetUri) {
                m["targetUri"] = params.targetUri
            }

            // Now redirect back to the login page.
            redirect(action: "login", params: m)
        }
    }

    def signOut = {
        // Log the user out of the application.
        def principal = SecurityUtils.subject?.principal
        SecurityUtils.subject?.logout()
        // For now, redirect back to the home page.
        if (ConfigUtils.getCasEnable() && ConfigUtils.isFromCas(principal)) {
            redirect(uri:ConfigUtils.getLogoutUrl())
        }else {
            //redirect(uri: "/")
             redirect(action: "login")
        }
        ConfigUtils.removePrincipal(principal)
    }

    def unauthorized = {
        render "You do not have permission to access this page."
    }
}
